package com.wzxy.nc.controller;

import java.util.HashSet;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.wzxy.nc.entity.SysRole;
import com.wzxy.nc.entity.SysUser;
import com.wzxy.nc.service.ISysRoleService;
import com.wzxy.nc.service.ISysUserService;
import com.wzxy.nc.util.HttpSessionUtil;
import com.wzxy.nc.util.JsonResultUtil;
import com.wzxy.nc.util.SysConstant;

@Controller
public class UserController extends AbsBaseController{

	/**  */
	private static final long serialVersionUID = 4028742272125079464L;
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	private static final String LOGIN_ERROR = "用户名或密码错误";
	
	private SysUser user;
	
	@Autowired
	private ISysUserService userService;
	
	@Autowired
	private ISysRoleService roleService;
	
	private List<SysRole> roles;
	
	/**
	 * shiro 登陆
	 * @return
	 */
	public String login(){
		SysUser sessionUser = HttpSessionUtil.getCurrentUser();
		// 说明用户已经登陆过了
		if(sessionUser != null){
    		super.setForwardPage("/WEB-INF/pages/common/main.jsp");   		
    		return SUCCESS;
		}
		
		if(user == null){
			return "relogin";
		}
		
		String username = user.getUsername();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
		//获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);  
        }catch(UnknownAccountException uae){  
            return toLoginPage("未知账户");
        }catch(IncorrectCredentialsException ice){  
			return toLoginPage("密码不正确");
        }catch(LockedAccountException lae){  
            return toLoginPage("账户已锁定");
        }catch(ExcessiveAttemptsException eae){   
            return toLoginPage("用户名或密码错误次数过多");
        }catch(AuthenticationException ae){  
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景   
            ae.printStackTrace();  
            return toLoginPage("用户名或密码不正确");
        }
        
        //验证是否登录成功  
        if(currentUser.isAuthenticated()){  
            logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
    		super.setForwardPage("/WEB-INF/pages/common/main.jsp");   		
    		return SUCCESS;
        }else {
        	token.clear();
            return toLoginPage(LOGIN_ERROR);
        }	
	}
	
	/**
	 * 跳转到登陆页面
	 * @param msg
	 * @return
	 */
	private String toLoginPage(String msg){
        super.getRequest().setAttribute("msg", msg);
		super.setForwardPage("login.jsp");
		return SUCCESS;
	}
	
	/**
	 * 用户列表
	 * @return
	 */
	public String list(){
		List<SysUser> userList = null;
		userList = userService.findByUser(user);
		super.getRequest().setAttribute("list", userList);
		super.setForwardPage("/WEB-INF/pages/user/user-list.jsp");	
		return SUCCESS;
	}
	
	/**
	 * 导出 excel
	 * @return
	 */
	public String download(){
		List<SysUser> list = userService.findAll();		
		return super.download(list, SysUser.class, "用户数据");
	}
	
	/**
	 * 新增用户
	 * @return
	 */
	public String insert(){
		if(user != null) {
			user.setRoles(new HashSet<SysRole>(roles));
			userService.insert(user);
		}	
		dataMap = JsonResultUtil.success();
		return JSON;
	}
	
	/**
	 * 打开新增用户的页面
	 * @return
	 */
	public String openInsertView(){
		//查询所有的角色
		List<SysRole> roles = roleService.findAll();		
		//把查出来的角色传到页面
		super.getRequest().setAttribute("roles", roles);
		super.setForwardPage("/WEB-INF/pages/user/user-insert.jsp");	
		return SUCCESS;
	}
	
	public String delete(){
		if(user != null && user.getId() != null){
			userService.delete(user.getId());
		}
		dataMap = JsonResultUtil.success();
		return JSON;
	}
	
	public void testWebSocket(){
		userService.testWebSocket();
	}
	
	/** 接收参数通过get/set的方式,可以百度struts2接值 */
	public SysUser getUser() {
		return user;
	}

	public void setUser(SysUser user) {
		this.user = user;
	}

	public List<SysRole> getRoles() {
		return roles;
	}

	public void setRoles(List<SysRole> roles) {
		this.roles = roles;
	}
	
	

}
